<template> 
  <div>
    <el-upload
      ref="upload"
      drag
      action=""
      :data="useOss?dataObj:null"
      list-type="picture"
      :multiple="false"
      :show-file-list="showFileList"
      :on-change="handleChange"
      :file-list="fileList"
      :before-upload="handleBeforeUpload"
      :on-remove="handleRemove"
      :http-request="handleUpload"
      :on-preview="handlePreview"
    >
      <i class="el-icon-upload"/>
      <div class="el-upload__image">将图片拖到此处，或<em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png图片，且不超过500kb</div>
    </el-upload>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" height="100%" :src="fileList[0].url" alt="">
    </el-dialog>

  </div>
</template>


<script>
  import uploadApi from "@/api/system/upload-api";
  export default {
    name: 'SingleUpload',
    props: {
      value: String,
    },
    data() {
      return {
        form: {
          id: '',
          title: '',
          pic: '',
          url: '',
          reveal: '',
          type: ''
        },
        dataObj: {
          policy: '',
          signature: '',
          key: '',
          ossaccessKeyId: '',
          dir: '',
          uploadFileList: [],
          host: ''

          // callback:'',
        },
        dialogVisible: false,
        useOss: false, // 使用oss->true;使用MinIO->false
        ossUploadUrl: 'http://macro-oss.oss-cn-shenzhen.aliyuncs.com',
        minioUploadUrl: 'http://localhost:8888/api/upload'
        // :action="useOss?ossUploadUrl:minioUploadUrl"
      };
    },
    computed: {
      imageUrl() {
        return this.value;
      },
      imageName() {
        if (this.value != null && this.value !== '') {
          return this.value.substr(this.value.lastIndexOf("/") + 1);
        } else {
          return null;
        }
      },
      fileList() {
        return [{
          name: this.imageName,
          url: this.imageUrl
        }]
      },
      showFileList: {
        get: function() {
          return this.value !== null && this.value !== '' && this.value !== undefined;
        },
        set: function(newValue) {
        }
      }
    },
    methods: {
      emitInput(val) {
        this.$emit('input', val)
      },

      handleChange(file, fileList) {
        console.log(file)
        // 将最后一个选择的文件赋值给文件列表
        if (fileList && fileList.length > 1) {
          fileList = [file]
        }
        this.uploadFileList = fileList
        this.form.pic = URL.createObjectURL(file.raw);
      },
      handleRemove(file, fileList) {
        this.emitInput('');
      },
      handlePreview(file) {
        this.dialogVisible = true;
        console.log(file);
      },
      // beforeUpload(file) {
      //     console.log(file)
      //   const _self = this;
      //   if (!this.useOss) {
      //     // 不使用oss不需要获取策略
      //     return true;
      //   }
      //   return new Promise((resolve, reject) => {
      //     policy().then(response => {
      //       _self.dataObj.policy = response.data.policy;
      //       _self.dataObj.signature = response.data.signature;
      //       _self.dataObj.ossaccessKeyId = response.data.accessKeyId;
      //       _self.dataObj.key = response.data.dir + '/${filename}';
      //       _self.dataObj.dir = response.data.dir;
      //       _self.dataObj.host = response.data.host;
      //       // _self.dataObj.callback = response.data.callback;
      //       resolve(true)
      //     }).catch(err => {
      //       console.log(err)
      //       reject(false)
      //     })
      //   })
      // },
      handleBeforeUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!isLt2M) {
          this.$message.error('头像大小不能超过 2MB!')
        }
        return isLt2M
      },
      // handleUploadSuccess(res, file) {
      //     console.log(file)
      //   this.showFileList = true;
      //   this.fileList.pop();
      //   let url = this.dataObj.host + '//' + this.dataObj.dir + '/' + file.name;
      //   if (!this.useOss) {
      //     // 不使用oss直接获取图片路径
      //     url = file.url;
      //   }
      //
      //   console.log(url)
      //   this.fileList.push({ name: file.name, url: url });
      //   this.emitInput(this.fileList[0].url);
      // },
      handleUpload(param) {
        var formUrl = '';
        const formData = new FormData()
        formData.append("file", param.file)
        formData.append("type", param.type)
        // 文件上传后，调用修改用户头像方法
        uploadApi.upload(formData).then(response => {
          formUrl = response.data;
          if (response.code === 200) {
            this.fileList[0].url = response.data
          } else {
            throw response.message
          }
        }).then(() => {
          this.showFileList = true;
          this.fileList.pop();
          let url = this.dataObj.host + '//' + this.dataObj.dir + '/' + param.file.name;
          if (!this.useOss) {
            // 不使用oss直接获取图片路径
            url = formUrl;
          }

          console.log(url)
          this.fileList.push({ name: param.file.name, url: url });
          this.emitInput(this.fileList[0].url);
        })
      }
    }
  }
</script>
<style>

</style>


